﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data.Linq.Mapping;
using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(ICategory))]
    public partial class Category : Entity, ICategory
    {
        //only for query
        [AssociationAttribute(Name = "Category_Category", Storage = "_Category1", ThisKey = "ParentId", OtherKey = "Id", IsForeignKey = true)]
        [ColumnAttribute(IsDbGenerated = false, AutoSync = AutoSync.Never, UpdateCheck = UpdateCheck.Never)]
        public Category Parent
        {
            get;
            set;
        }

        ICategory _Parent;
        ICategory ICategory.Parent
        {
            get
            {
                if (this._Parent == null && this.ParentId.HasValue)
                {
                    this._Parent = this.DataContext.Categories.Where(i => i.Id == this.ParentId)
                        .FirstOrDefault(); 
                }

                return this._Parent;
            }
            set
            {
                this._Parent = value;
                if (value == null)
                {
                    this.ParentId = null;
                }
                else
                {
                    this.ParentId = value.Id;
                }
            }
        }

        //only for query
        [global::System.Data.Linq.Mapping.AssociationAttribute(Name = "Category_Category", Storage = "_Categories", ThisKey = "Id", OtherKey = "ParentId")]
        [ColumnAttribute(IsDbGenerated = false, AutoSync = AutoSync.Never, UpdateCheck = UpdateCheck.Never)]
        public IQueryable<Category> Children
        {
            get;
            set;
        }

        IQueryable<ICategory> ICategory.Children
        {
            get
            {
                return this.DataContext.Categories.Where(i => i.ParentId == this.Id);
            }
        }

        //only for Products.Count(),to build sql command text.
        [global::System.Data.Linq.Mapping.AssociationAttribute(Name = "Category_CategoryProduct", Storage = "_CategoryProducts", ThisKey = "Id", OtherKey = "CategoryId")]
        [ColumnAttribute(IsDbGenerated = false, AutoSync = AutoSync.Never, UpdateCheck = UpdateCheck.Never)]
        public IQueryable<CategoryProduct> Products
        {
            get;
            set;
        }

        IQueryable<IProduct> ICategory.Products
        {
            get
            {
                return this.DataContext
                    .CategoryProducts
                    .Where(i => i.CategoryId == this.Id)
                    .Select(i => i.Product);
            }
        }

    }
}
